package com.hxzy.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.web.resp.R;
import com.hxzy.module.admin.resp.AccountDetailResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Api(tags = "总部后台-账户相关的Api")
@RequestMapping(value = "/admin")
@RestController
public class AdminController {

    @ApiOperation(value = "根据id查询")
    @GetMapping(value = "/account/{id}")
    public R<AccountDetailResp> adminAccountFindById(@PathVariable(value = "id") String accountId){
        //通过用程调用http请求
        AccountDetailResp accountDetailResp = this.restTemplateNacosServiceDiscoveryGetUrl(accountId);

        //获取当前account门户店信息

        return R.okHasData(accountDetailResp);
    }

    @Autowired
    private DiscoveryClient  discoveryClient;

    //轮询
    private AtomicInteger  atomicInteger=new AtomicInteger(0);

    /**
     * restTemplate+ nacos服务发现 (轮询)
     * @param accountId
     * @return
     */
    private AccountDetailResp restTemplateNacosServiceDiscoveryGetUrl(String accountId){
        List<ServiceInstance> adminList = this.discoveryClient.getInstances("admin");

        //轮询
        int index= atomicInteger.getAndIncrement() %  adminList.size();

        ServiceInstance serviceInstance = adminList.get(index);
        //  0(0-n) %2=  0  1  0  1  0  1  0  1  0  1

        RestTemplate restTemplate=new RestTemplate();
        String hostName=serviceInstance.getHost();   //localhost    192.168.20.160
        int port = serviceInstance.getPort();

        String url=StrUtil.format("http://{}:{}/admin/account/"+accountId,  hostName,port);
        System.out.println(url);
        R r = restTemplate.getForObject(url, R.class);
        return getAccountDetailResp(r);
    }


    /**
     * 使用restTemplate
     * @param accountId
     * @return
     */
    private AccountDetailResp restTemplateGetUrl(String accountId){
        RestTemplate restTemplate=new RestTemplate();
        String url="http://localhost:8025/admin/account/"+accountId;
        R r = restTemplate.getForObject(url, R.class);
        return getAccountDetailResp(r);
    }


    private AccountDetailResp remoteGetUrl(String accountId){
        try {
            URL url = new URL("http://localhost:8025/admin/account/"+accountId); // 替换为您要发送请求的URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");


            //使用流方式来读取数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;

            StringBuffer out = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                out.append(inputLine);
            }
            in.close();
            connection.disconnect();


            //如果不为空，有值  R<AccountDetailResp>
            if(StrUtil.isNotBlank(out.toString())){
                R r= JSONUtil.toBean(out.toString(), R.class);
                return getAccountDetailResp(r);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new RuntimeException("远程访问或解析数据失败");
    }

    public static AccountDetailResp getAccountDetailResp(R r) {
        if(r.getCode().intValue()== AckCode.SUCCESS.getCode()){
            Object data = r.getData();
            //再转r = {R@7815}
            String jsonStr=JSONUtil.toJsonStr(data);
            //再转
            return JSONUtil.toBean(jsonStr, AccountDetailResp.class);
        }else{
            throw new RuntimeException( r.getMsg());
        }
    }


}
